package com.wclass.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wclass.entity.BaseId;
import com.wclass.mapper.BaseIdMapper;
import com.wclass.service.IBaseIdService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自插入id记录表 服务实现类
 * </p>
 *
 * @author SEN
 * @since 2019-04-22
 */
@Service
public class BaseIdServiceImpl extends ServiceImpl<BaseIdMapper, BaseId> implements IBaseIdService {

    /**
     * 根据类型获取id值
     * @param type 1：user，2：course，3：organ
     * @return
     */
    public BaseId getNoUseId(int type) {
        EntityWrapper<BaseId> ew = new EntityWrapper<>();
        if (type == 1) {
            ew.eq("user_state", "0");
        } else if (type == 2) {
            ew.eq("course_state", "0");
        } else if (type == 3) {
            ew.eq("organ_state", "0");
        }

        List<BaseId> idList = this.selectList(ew);
        if (idList.size() == 0) {
            insertIdList();
            return getNoUseId(type);
        }
        BaseId baseId = idList.get(0);
        return baseId;
    }

    public void insertIdList() {
        for (int i = 0;i < 100;i++) {
            int random = (int) (Math.random() * 100000000 + 10000000);
            int count = this.selectCount(new EntityWrapper<BaseId>().eq("id", random));
            if (count == 0 && random < 100000000) {
                BaseId baseId = new BaseId();
                baseId.setId(Long.parseLong(random + ""));
                baseId.setCrtTime(new Date());
                baseId.setUserState(0);
                baseId.setCourseState(0);
                baseId.setOrganState(0);
                this.insert(baseId);
            }
        }
    }

}
